import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { LocalStorage } from '../../utils/localstorage';
import { Title } from '@angular/platform-browser';
import { HttpService } from "../../http/http.service";
import { NotifyService } from "../../utils/notify.service";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: [ './login.component.styl' ],
  providers: [ LocalStorage ]
})
export class LoginComponent implements OnInit {
  validateForm: FormGroup;
  passwordVisible = false;
  page1: Boolean = true;
  page2: Boolean = false;

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private titleService: Title,
    private http: HttpService,
    private notify: NotifyService
  ) {
    this.titleService.setTitle("爱波瑞精益制造测评系统-登录");
  }

  get userName() {
    return this.validateForm.get('userName');
  }

  get password() {
    return this.validateForm.get('password');
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (!this.validateForm.valid) return;

    let loginData: any = {};
    loginData.phone = this.userName.value;
    loginData.oldpwd = this.password.value;

    this.http.postNoToken("bas/user/login", loginData).subscribe(res => {
      if (res.err == '0') {
        LocalStorage.saveToken(res.data);
        this.router.navigateByUrl('wel');
      } else {
        this.notify.error(res.errMsg).subscribe();
      }
    });
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [ null, [ Validators.required, Validators.minLength(6), Validators.maxLength(20) ] ],
      password: [ null, [ Validators.required, Validators.minLength(6), Validators.maxLength(10) ] ],
      remember: [ true ]
    });
  }

  onGotoRegister() {
    LocalStorage.removeToken();
    this.router.navigateByUrl("/register");
  }

  show(i): void {
    if (i === 1) {
      this.page1 = true;
      this.page2 = false;
    } else if (i === 2) {
      this.page2 = true;
      this.page1 = false;
    }
  }
}
